package com.magnate.software.upload.manager;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.RandomAccessFile;

/**
 * 上传控制器
 *
 * @author WangYang
 * @version 1.0
 * @datetime 2015/11/26 17:59
 */
@RestController
@RequestMapping(value = "/upload")
public class UploadController {

    private static final Logger logger = LoggerFactory.getLogger(UploadController.class);

    @RequestMapping(value = "", method = RequestMethod.POST)
    @ResponseStatus(HttpStatus.OK)
    public void upload(
            @RequestHeader("Content-Range") String contentRange,
            @RequestParam("file") MultipartFile file) throws Exception {
        logger.debug("文件上传：Content-Range " + contentRange);
        logger.debug("文件上传：文件大小 " + file.getSize());

        String fileName = "1.rar";
        String[] contentRanges = contentRange.replace("bytes ", "").split("/");
        String[] ranges = contentRanges[0].split("-");

        RandomAccessFile raFile = new RandomAccessFile(new File("d:/" + fileName), "rw");
        raFile.seek(Integer.parseInt(ranges[0]));
        raFile.write(file.getBytes());
        raFile.close();
    }

    @RequestMapping(value = "get", method = RequestMethod.POST)
    @ResponseStatus(HttpStatus.OK)
    public void post(@RequestParam("file_name") String fileName) throws Exception {
        logger.debug("文件名称：" + fileName);
    }

    @RequestMapping(value = "", method = RequestMethod.GET)
    @ResponseStatus(HttpStatus.OK)
    public void get() throws Exception {
        logger.debug("这是一个请求！");
    }

}
